package com.navi.loaddata.job;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.navi.loaddata.core.job.QuartzManage;
import com.navi.loaddata.core.mysqlEntity.EtlConfD;
import com.navi.loaddata.core.util.LoggerUtil;
import com.navi.loaddata.loadService.IEtlConfServices;
import java.beans.PropertyVetoException;
import javax.annotation.PostConstruct;
import org.quartz.CronExpression;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author jay
 */
@Service
public class LoadJobMain {
    private static final Logger logger = LoggerFactory.getLogger(LoadJobMain.class);
    private LoggerUtil loggerUtil = new LoggerUtil(this.getClass());

    @Autowired
    private IEtlConfServices etlConfServices;

    @Autowired
    private QuartzManage quartzManage;

    @Value("${job.projectName}")
    private String projectName;

    @Value("${job.groupName}")
    private String jobGroupName;

    @Value("${job.name}")
    private String jobName;

    @Value("${log.home}")
    private String logHome;

    @Value("${spring.profiles.active}")
    private String active;

    @Scheduled(cron = "*/5 * * * * ?")
    public void loadMain() throws SchedulerException, IllegalAccessException, InstantiationException, ClassNotFoundException  {
        logger.info("Scan job.");

        if("other".equals(logHome)&&"prod".equals(active)){
            logger.error("未设定logHome");
            return;
        }

        if("TEST".equals(projectName)){
            logger.error("未设定projectName");
            return;
        }
        if("TEST".equals(jobGroupName)){
            logger.error("未设定jobGroupName");
            return;
        }
        if("TEST".equals(jobName)){
            logger.error("未设定jobName");
            return;
        }


        List<EtlConfD> etlConfDList = etlConfServices.getEtlConf(projectName, jobGroupName, jobName);
        etlConfDList.forEach(etlConfD -> {
            if (!CronExpression.isValidExpression(etlConfD.getCronExpression())){
                logger.error("cron表达式格式错误"); //todo 打印明细 & 存储错误信息
            }

            if(!"Y".equals(etlConfD.getValidFlg())){//Valig_Flg='N'
                try {
                    quartzManage.deleteJob(etlConfD);
                } catch (SchedulerException e) {
                    logger.error(LoggerUtil.stackTraceToString(e));
                }
            }else {
                try {
                    quartzManage.addJob(etlConfD);
                } catch (SchedulerException | ClassNotFoundException | IllegalAccessException | InstantiationException e) {
                    logger.error(LoggerUtil.stackTraceToString(e));
                }
            }
        });
    }
}
